import React from 'react';
import {PageLoading, Settings as LayoutSettings} from '@ant-design/pro-layout';
import {Badge, Button, message as msg, notification} from 'antd';
// @ts-ignore
import {history, RequestConfig, RunTimeLayoutConfig} from 'umi';
import RightContent from '@/components/RightContent';
import defaultSettings from '../config/defaultSettings';
import {MenuDataItem} from "@ant-design/pro-layout/lib/typings";
import {ResponseError} from 'umi-request';
import {getCurrentUser} from "@/pages/sys/UserList/service";
import {
  AuditOutlined,
  FileTextOutlined,
  HomeOutlined, MonitorOutlined,
  SettingOutlined,
  SmileOutlined,
  TableOutlined,
  ToolOutlined
} from "@ant-design/icons";
import {treeDataCurrentUser} from "@/pages/sys/MenuList/service";

/**
 * 获取用户信息比较慢的时候会展示一个 loading
 */
export const initialStateConfig = {
  loading: <PageLoading/>,
};

export async function getInitialState(): Promise<{
  settings?: LayoutSettings;
  currentUser?: API.CurrentUser;
  fetchUserInfo?: () => Promise<API.CurrentUser | undefined>;
  menuData?: MenuDataItem[];
}> {
  const fetchUserInfo = async () => {
    try {
      const currentUser = await getCurrentUser();
      return currentUser;
    } catch (error) {
      history.push('/user/login');
    }
    return undefined;
  };
  // 获取菜单
  // @ts-ignore
  let menuList = await treeDataCurrentUser() || [];
  // 如果是登录页面，不执行
  if (history.location.pathname !== '/user/login') {
    const currentUser = await fetchUserInfo();
    return {
      fetchUserInfo,
      currentUser,
      settings: defaultSettings,
      menuData: menuList.data || []
    };
  }
  return {
    fetchUserInfo,
    settings: defaultSettings,
    menuData: menuList.data || []
  };
}

// @ts-ignore
export const layout: RunTimeLayoutConfig = ({initialState}) => {
  return {
    rightContentRender: () => <RightContent/>,
    disableContentMargin: false,
    // footerRender: () => <Footer/>,
    onPageChange: () => {
      const {location} = history;
      // 如果没有登录，重定向到 login
      if (!initialState?.currentUser && location.pathname !== '/user/login') {
        history.push('/user/login');
      }
    },
    menuDataRender: (menuData: any) => {
      return initialState && mappingIcon(initialState.menuData) || mappingIcon(menuData);
    },
    menuHeaderRender: undefined,
    // 自定义 403 页面
    // unAccessible: <div>unAccessible</div>,
    ...initialState?.settings,
  };
};

// const codeMessage = {
//   200: '服务器成功返回请求的数据。',
//   201: '新建或修改数据成功。',
//   202: '一个请求已经进入后台排队（异步任务）。',
//   204: '删除数据成功。',
//   400: '发出的请求有错误，服务器没有进行新建或修改数据的操作。',
//   401: '用户没有权限（令牌、用户名、密码错误）。',
//   403: '用户得到授权，但是访问是被禁止的。',
//   404: '发出的请求针对的是不存在的记录，服务器没有进行操作。',
//   405: '请求方法不被允许。',
//   406: '请求的格式不可得。',
//   410: '请求的资源被永久删除，且不会再得到的。',
//   422: '当创建一个对象时，发生一个验证错误。',
//   500: '服务器发生错误，请检查服务器。',
//   502: '网关错误。',
//   503: '服务不可用，服务器暂时过载或维护。',
//   504: '网关超时。',
// };

/**
 * 异常处理程序
 */
const errorHandler = (error: ResponseError) => {
  const {message, data, type} = error;
  // 判断是否为httpError，即是否为系统错误
  if (type === "HttpError") {
    // 系统错误
    if (data && data.status) {
      switch (data.status) {
        case 500:
          notification.error({
            message: `系统错误`,
            description: "系统错误，请联系管理员",
          });
          break;
      }
    } else {
      // 登录信息超时
      if (message === "TypeError: Failed to fetch") {
        msg.error("登录超时，1秒后将跳转到登录页面", 1, () => {
          if (document.referrer.indexOf("https://rp.jx139.com/login") == -1) {
            window.location.href = "https://rp.jx139.com/login"
          }
        })
      }
    }
  } else {
    // 非系统错误，参数校验失败等
    if (data && data.errorCode) {
      switch (data.errorCode) {
        case 400:
          msg.error(message)
        // notification.error({
        //   message: `操作失败`,
        //   description: message,
        // });
      }
    } else {
      // 登录信息超时
      if (message === "TypeError: Failed to fetch") {
        msg.error("登录超时，1秒后将跳转到登录页面", 1, () => {
          if (document.referrer.indexOf("https://rp.jx139.com/login") == -1) {
            window.location.href = "https://rp.jx139.com/login"
          }
        })
      }
    }
  }
  throw error;
};
export const request: RequestConfig = {
  errorHandler,
};

/**
 * 用于显示菜单图标
 */
const iconEnum = {
  smile: <SmileOutlined/>,
  home: <HomeOutlined/>,
  setting: <SettingOutlined/>,
  audit: <AuditOutlined/>,
  table: <TableOutlined/>,
  tool: <ToolOutlined/>,
  doc: <FileTextOutlined/>,
  mon: <MonitorOutlined/>,
};
// 将服务端获取的菜单 icon 字符串映射为对应的 icon Dom
const mappingIcon = (menuData: any) => {
  const {location} = history;
  const mappingMenu = menuData?.map((item: any) => (
    {
      ...item,
      name: item["badge"] != undefined ? (
        <Badge count={item.badge} offset={[-8, 8]} size={"small"}>
          <Button
            type="text"
            style={Object.assign({}, {paddingLeft: 0}, location.pathname.indexOf(item.path) === 0 ? {color: '#1890ff'} : {})}
            onClick={(event) => {
              // @ts-ignore
              event.target.style.color = '#1890ff';
            }}
            onMouseMove={(event) => {
              // @ts-ignore
              event.target.style.color = '#1890ff';
            }}
          >
            {item.name}
          </Button>
        </Badge>
      ) : item.name,
      key: item.path,
      icon: iconEnum[item.icon],
      children: item.children ? mappingIcon(item.children) : [],
    }
  ));
  return mappingMenu;
};
